package com.glodon.paas.account.security.cas.notification;

import static com.google.common.base.Strings.isNullOrEmpty;

import java.io.IOException;

import org.jasig.cas.services.RegisteredService;
import org.jasig.cas.services.ServicesManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.glodon.paas.account.security.spring.LoginUser;
import com.glodon.paas.account.service.util.PaasRegisteredServiceImpl;
import com.glodon.paas.util.HttpUtils;

/**
 * @author Don Li
 */
@Component
public class HttpCasNotificationManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpCasNotificationManager.class);

    @Autowired
    private ServicesManager servicesManager;

    public void sendInvalidateSessionNotification(String sourceServiceId, LoginUser user) {
        for (RegisteredService service : servicesManager.getAllServices()) {
            if (service instanceof PaasRegisteredServiceImpl) {
                String callback = ((PaasRegisteredServiceImpl) service).getLogoutCallbackUrl();
                //account id                
                if (service.getId() != 1 && !service.getServiceId().equals(sourceServiceId) && !isNullOrEmpty(callback)) {
                    try {
                        HttpUtils.sendDelete(callback + "?user_id=" + user.getId());
                    } catch (IOException e) {
                        LOGGER.error("Fail to send logout notification to service: {}, at url: {}", service.getName(), ((PaasRegisteredServiceImpl) service).getLogoutCallbackUrl());
                    }
                }
            }
        }
    }
}
